<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Menu extends Controller
{
    public function action_index()
    {
        $menu = View::factory('menu')
                        ->set('sections', $this->get_sections());
        Request::$current->response()->body($menu->render());        
    }
    
    public function get_sections($id_parent = 0)
    {
        $sections = array();
        $query = DB::query(Database::SELECT, "SELECT c1.id as `id`, c1.name as `name`, c1.href as `href`, c1.hide as `hide`, c1.id_parent as `id_parent`, (COUNT( c2.name )>0) as `subsections` 
                                                FROM  `sections` AS  `c1` 
                                                LEFT JOIN  `sections` AS  `c2` ON c2.id_parent = c1.id
                                                WHERE (c1.id_parent =$id_parent AND c1.hide='show')                                               
                                                GROUP BY c1.name
                                                ORDER BY c1.pos");
        $result = $query->execute();        
        foreach ($result as $section) {
            if($section['subsections'])
                $section['subsections'] = $this->get_sections($section['id']);
            else
                unset($section['subsections']);
            $sections[] = $section;
        }
        return $sections;
    }
}